package com.demo.fastjson2;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.demo.fastjson2.model.FastJsonEntity;
import com.demo.fastjson2.model.FastJsonEntity01;
import com.demo.fastjson2.model.FastJsonEntity02;
import org.junit.jupiter.api.Test;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author shenguangyang
 */
public class FastJson2Test {
    /**
     * 1. 将list转成json
     * 2. 将json转为list
     */
    @Test
    public void t01() {
        FastJsonEntity<List<FastJsonEntity01>> data = genDataOfFastJsonEntity01();
        String jsonData = JSON.toJSONString(data);
        System.out.println(jsonData);
        FastJsonEntity<List<FastJsonEntity01>> srcData =
                JSON.parseObject(jsonData, new TypeReference<FastJsonEntity<List<FastJsonEntity01>>>() {});
        System.out.println("end");
    }

    /**
     * json to obj 映射字段不同
     */
    @Test
    public void t02_JsonToObjForFieldDiff() {
        String jsonData = "{\"name\":\"sgy\",\"count\":10}";
        FastJsonEntity02 srcData = JSON.parseObject(jsonData, FastJsonEntity02.class);
        System.out.println(srcData);
    }

    /**
     * obj to json 将obj中某个字段名转成另一字段
     */
    @Test
    public void t03_ObjToJsonForFieldDiff() {
        FastJsonEntity02 data = FastJsonEntity02.builder().myCount(10).myName(UUID.randomUUID().toString()).build();
        String jsonData = JSON.toJSONString(data);
        System.out.println(jsonData);
    }

    public FastJsonEntity<List<FastJsonEntity01>> genDataOfFastJsonEntity01() {
        List<FastJsonEntity01> fastJsonEntity01s = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            fastJsonEntity01s.add(FastJsonEntity01.builder().count(i > 2 ? i : null).createTime(LocalDateTime.now())
                    .name(UUID.randomUUID().toString()).price(new BigDecimal("23")).build());
        }
        return FastJsonEntity.<List<FastJsonEntity01>>builder().data(fastJsonEntity01s).code(1).msg("ok").build();
    }
}
